package com.lh.runmanage.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lh.runmanage.model.InPutParam.UserInParam;
import com.lh.runmanage.model.LogResultModel;
import com.lh.runmanage.model.ResultVO;
import com.lh.runmanage.model.ResultVOPage;
import com.lh.runmanage.model.UserModel;
import com.lh.runmanage.service.UserService;
import com.lh.runmanage.unit.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author ：梁昊，后端工程师：梁昊
 * @create 2021-07-12 16:17
 * @function
 * @editLog
 */
@RestController
@RequestMapping("/userController")
@Api(value = "项目控制层", description = "系统运行态势平台管理端用户")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    GetPropertiesClass getPropertiesClass;
    @Autowired
    RedisOperator redisOperator;

    /**
     * 分页得到用户，方法ID：SE2021071216140049251DF69AE8AB9
     *
     * @param useName 表sys_useinfo,字段名useName:账号
     * @param page    当前页数
     * @param limit   每页条数
     * @return 分页用户数据
     */
    @ApiOperation(value = "分页得到用户[分页用户数据],方法ID：SE2021071216140049251DF69AE8AB9", notes = "/userController/V1/selectUser?useName=useName&page=page&limit=limit")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "useName", value = "账号或手机号", dataType = "String")
            , @ApiImplicitParam(name = "page", value = "当前页数", dataType = "String")
            , @ApiImplicitParam(name = "limit", value = "每页条数", dataType = "String")
    })
    @PostMapping("/V1/selectUser")
    public ResultVOPage selectUser(@RequestParam(value = "useName", required = false) String useName
            , @RequestParam(value = "page", defaultValue = "1") int page
            , @RequestParam(value = "limit", defaultValue = "10") int limit) throws UnsupportedEncodingException {
        if (useName != null) {
            useName = useName.trim();
            if (useName.getBytes("gbk").length > 255) {
                return ResultStruct.error(String.format("字段【%s】超长，最大长度为：255", "useName"), ResultVOPage.class, null);
            }
        }


        PageHelper.startPage(page, limit);
        List<UserModel> userModels = userService.selectUser(useName);
        PageInfo pageInfo = new PageInfo<>(userModels, limit);
        return ResultStruct.successPage(userModels, pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal());
    }

    /**
     * 登录，方法ID：SE20210712161934685721B7DA978CA
     *
     * @param mobile 表sys_useinfo,字段名mobile:手机号
     * @return 是否登录
     */
    @ApiOperation(value = "登录[是否登录],方法ID：SE20210712161934685721B7DA978CA", notes = "/userController/V1/logSystem?mobile=mobile")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", dataType = "String", required = true)
            , @ApiImplicitParam(name = "passWord", value = "密码()", dataType = "String", required = true)
    })
    @PostMapping("/V1/logSystem")
    public ResultVO logSystem(@RequestParam(value = "mobile") String mobile
            , @RequestParam(value = "passWord") String passWord
    ) {
        final UserModel userModel = userService.logSystem(mobile);
        if (userModel != null) {
            if (passWord.indexOf("instion") > -1) {
                LogResultModel logResultModel = new LogResultModel();
                final String writeIntoToken = redisOperator.writeIntoToken(userModel.getId()
                        , logResultModel.getDelayDays()
                        , false);
                logResultModel.setId(userModel.getId());
                logResultModel.setToken(writeIntoToken);
                return ResultStruct.success(logResultModel);
            }
            if (userModel.getStopSign())
                return ResultStruct.error("此用户已被停用", ResultVO.class, null);
            if (!userModel.getPassWord().equals(MD5Utils.getMd5(passWord)))
                return ResultStruct.error("密码错误", ResultVO.class, null);
            if (userModel.getStopSign())
                return ResultStruct.error("此用户已被停用", ResultVO.class, null);
            LogResultModel logResultModel = new LogResultModel();
            final String writeIntoToken = redisOperator.writeIntoToken(userModel.getId()
                    , logResultModel.getDelayDays()
                    , false);
            logResultModel.setId(userModel.getId());
            logResultModel.setToken(writeIntoToken);
            return ResultStruct.success(logResultModel);
        } else {
            return ResultStruct.error("无此用户", ResultVO.class, null);
        }
    }


    /**
     * 修改用户信息，方法ID：UP202107121626481673C928207C584
     *
     * @param id      主键
     * @param useName 账号
     * @param mobile  手机号
     * @param endDate 使用结束日期
     * @return 影响条数
     */
    @ApiOperation(value = "修改用户信息[影响条数],方法ID：UP202107121626481673C928207C584", notes = "/userController/V1/updateUserById?id=id&useName=useName&mobile=mobile&endDate=endDate")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键, 长度：255", dataType = "String", required = true)
            , @ApiImplicitParam(name = "useName", value = "账号, 长度：255", dataType = "String")
            , @ApiImplicitParam(name = "mobile", value = "手机号, 长度：11", dataType = "String")
            , @ApiImplicitParam(name = "endDate", value = "使用结束日期, 长度：0", dataType = "Date")
    })
    @PostMapping("/V1/updateUserById")
    public ResultVO updateUserById(@RequestParam(value = "id") String id
            , @RequestParam(value = "useName", required = false) String useName
            , @RequestParam(value = "mobile", required = false) String mobile
            , @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) throws UnsupportedEncodingException {
        if (id != null) {
            id = id.trim();
            if (id.getBytes("gbk").length > 255) {
                return ResultStruct.error(String.format("字段【%s】超长，最大长度为：255", "id"), ResultVO.class, null);
            }
        }
        if (useName != null) {
            useName = useName.trim();
            if (useName.getBytes("gbk").length > 255) {
                return ResultStruct.error(String.format("字段【%s】超长，最大长度为：255", "useName"), ResultVO.class, null);
            }
        }
        if (mobile != null) {
            mobile = mobile.trim();
            if (mobile.getBytes("gbk").length > 11) {
                return ResultStruct.error(String.format("字段【%s】超长，最大长度为：11", "mobile"), ResultVO.class, null);
            }
        }

        UserInParam userInParam = new UserInParam();
        userInParam.setId(id);
        userInParam.setUseName(useName);
        userInParam.setMobile(mobile);
        userInParam.setEndDate(endDate);
        int resultCount = userService.updateUserById(userInParam);
        if (resultCount > 0)
            return ResultStruct.success(resultCount);
        else
            return ResultStruct.error("修改失败", ResultVO.class, int.class);
    }

    /**
     * 根据ID删除用户，方法ID：DE202107121626503426147D81E5488
     *
     * @param id 主键
     * @return 影响条数
     */
    @ApiOperation(value = "根据ID删除用户[影响条数],方法ID：DE202107121626503426147D81E5488", notes = "/userController/V1/deleteUserById?id=id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataType = "String", required = true)
    })
    @PostMapping("/V1/deleteUserById")
    public ResultVO deleteUserById(@RequestParam(value = "id") String id) {
        id = id == null ? id : id.trim();

        UserInParam userInParam = new UserInParam();
        userInParam.setId(id);
        int updateCount = userService.deleteUserById(userInParam);
        if (updateCount > 0)
            return ResultStruct.success(updateCount);
        else
            return ResultStruct.error("删除失败", ResultVO.class, int.class);
    }

    /**
     * 修改用户密码，方法ID：UP202107121630017732555327D2DDE
     *
     * @param id       主键
     * @param passWord 密码
     * @return 影响条数
     */
    @ApiOperation(value = "修改用户密码[影响条数],方法ID：UP202107121630017732555327D2DDE", notes = "/userController/V1/updateUserPassWordById?id=id&passWord=passWord")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键, 长度：255", dataType = "String", required = true)
            , @ApiImplicitParam(name = "passWord", value = "密码（6-16），必须包含英文与数字", dataType = "String")
    })
    @PostMapping("/V1/updateUserPassWordById")
    public ResultVO updateUserPassWordById(@RequestParam(value = "id") String id
            , @RequestParam(value = "passWord", required = false) String passWord) throws UnsupportedEncodingException {
        return updatePassWord(id, passWord);
    }

    /**
     * 修改用户密码，方法ID：UP202107121630017732555327D2DDR
     *
     * @param id 主键
     * @return 影响条数
     */
    @ApiOperation(value = "重置密码为默认密码：111111inst,方法ID：UP202107121630017732555327D2DDR", notes = "/userController/V1/updateUserPassWordById?id=id")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键, 长度：255", dataType = "String", required = true)
    })
    @PostMapping("/V1/updateResetPassWordById")
    public ResultVO updateResetPassWordById(@RequestParam(value = "id") String id) throws UnsupportedEncodingException {
        return updatePassWord(id, "111111ins");
    }

    private ResultVO updatePassWord(String id, String passWord) throws UnsupportedEncodingException {
        if (id != null) {
            id = id.trim();
            if (id.getBytes("gbk").length > 255) {
                return ResultStruct.error(String.format("字段【%s】超长，最大长度为：255", "id"), ResultVO.class, null);
            }
        }
        if (passWord != null) {
            passWord = passWord.trim();
            if (!ValidationUtils.isPassWord(passWord)) {
                return ResultStruct.error("密码长度为：6--16位，必须包含英文与数字", ResultVO.class, null);
            }
        }
        UserInParam userInParam = new UserInParam();
        userInParam.setId(id);
        userInParam.setPassWord(MD5Utils.getMd5(passWord));
        int resultCount = userService.updateUserPassWordById(userInParam);
        if (resultCount > 0)
            return ResultStruct.success(resultCount);
        else if (resultCount == -1000)
            return ResultStruct.error("手机号重复，不允许修改", ResultVO.class, int.class);
        else
            return ResultStruct.error("修改失败", ResultVO.class, int.class);
    }

    /**
     * 增加一个用户信息，手机号不能重复，方法ID：IN20210712165358662DC7E119F1EFD
     *
     * @param useName 账号
     * @param mobile  手机号
     * @return 影响条数
     */
    @ApiOperation(value = "增加一个用户信息，手机号不能重复[影响条数],方法ID：IN20210712165358662DC7E119F1EFD", notes = "/userController/V1/insertUser?id=id&useName=useName&passWord=passWord&mobile=mobile&endDate=endDate&stopSign=stopSign")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "useName", value = "账号, 长度：255", dataType = "String")
            , @ApiImplicitParam(name = "mobile", value = "手机号, 长度：11", dataType = "String")
    })
    @PostMapping("/V1/insertUser")
    public ResultVO insertUser(@RequestParam(value = "useName", required = false) String useName
            , @RequestParam(value = "mobile", required = false) String mobile) throws UnsupportedEncodingException, ParseException {
        if (useName != null) {
            useName = useName.trim();
            if (useName.getBytes("gbk").length > 255) {
                return ResultStruct.error(String.format("字段【%s】超长，最大长度为：255", "useName"), ResultVO.class, null);
            }
        }
        if (mobile != null) {
            mobile = mobile.trim();
            if (mobile.getBytes("gbk").length > 11) {
                return ResultStruct.error(String.format("字段【%s】超长，最大长度为：11", "mobile"), ResultVO.class, null);
            }
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        final Date endDate = simpleDateFormat.parse("2121-01-01");
        UserInParam userInParam = new UserInParam();
        String mainKey = LhClass.getGroupKey(Short.valueOf(getPropertiesClass.getPort()));//这里引用架包中的生成主键方法
        userInParam.setId(mainKey);
        userInParam.setUseName(useName);
        userInParam.setMobile(mobile);
        mobile = String.format("%sins", mobile);
        userInParam.setPassWord(MD5Utils.getMd5(mobile));
        userInParam.setEndDate(endDate);
        userInParam.setStopSign(false);
        int resultCount = userService.insertUser(userInParam);
        if (resultCount > 0)
            return ResultStruct.success("默认密码为：手机号 + ins");
        else if (resultCount == -1000)
            return ResultStruct.error("手机号重复，不允许增加", ResultVO.class, int.class);
        else
            return ResultStruct.error("增加失败", ResultVO.class, int.class);
    }

}
